@tool
extends GridContainer

class_name ItemsGrid


# item_slot_scene, btn_group 必须在 inventory 前面，因为inventory要使用到item_slot_scene, btn_group的值
@export var item_slot_scene: PackedScene
@export var btn_group: ButtonGroup
@export var inventory: Inventory:
    set(value):
        if inventory == value:
            return
        inventory = value
        _auto_crate_item_slots()
        inventory_changed.emit()


signal inventory_changed

var selected_slot: ItemSlot



func _ready() -> void:
    inventory_changed.connect(_update_display)
    if not Engine.is_editor_hint():
        inventory.items_updated.connect(_update_display)
        _update_display()

        btn_group.pressed.connect(
            func(btn):
                selected_slot = btn
                print(selected_slot)
        )
    

func _remove_all_slots() -> void:
    for node in get_children():
        remove_child(node)
        node.queue_free()


func _auto_crate_item_slots() -> void:
    
    _remove_all_slots()
    if inventory == null: return
    
    for i in range(inventory.list.size()):
        var slot := item_slot_scene.instantiate() as ItemSlot
        add_child(slot)
        slot.name = "ItemSlot%d" % i
        if not Engine.is_editor_hint():
            slot.item_data.setup(inventory, i)
            slot.item_count = 0
            slot.button_group = btn_group


func _update_display() -> void:
    for i in range(inventory.list.size()):
        var slot := get_child(i) as ItemSlot
        if inventory.list[i] == null:
            slot.item_texture = null
            slot.item_count = 0
        else:
            slot.item_texture = InventoryManager.get_item(inventory.list[i].id).icon
            slot.item_count = inventory.list[i].count



